package com.yfh.study.manager.application;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.nio.charset.StandardCharsets;

@ComponentScan("com.yfh")
@SpringBootApplication
@MapperScan("com.yfh.study.manager.dao")
public class ConfigApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigApplication.class,args);
    }
    @Bean
    public CorsFilter getCirsFilter(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedMethod("*");//所有请求类型跨域 GET POST
        corsConfiguration.addAllowedHeader("*");//允许所有请求头部类型跨域
        corsConfiguration.addAllowedOrigin("*");//允许所有主机地址跨域
        corsConfiguration.setAllowCredentials(true);//允许cookie跨域

        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(corsConfigurationSource);
    }

    /**
     * 处理http请求乱码
     * @return
     */
    @Bean
    public RestTemplate restTemplatMessageSdk() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(1800000);
        httpRequestFactory.setConnectTimeout(1800000);
        httpRequestFactory.setReadTimeout(1800000);
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        StringHttpMessageConverter t = new StringHttpMessageConverter();
//设置为false就可以修改header中的accept-charset属性
        t.setWriteAcceptCharset(false);
        t.setDefaultCharset(StandardCharsets.UTF_8);
        restTemplate.getMessageConverters().add(0,t);
        return restTemplate;
    }

    /**
     * websocker注册路由有gogame这个路由
     * @return
     */
    @Bean
    public ServerEndpointExporter getServerEndpointExporter(){return new ServerEndpointExporter();}
}
